import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { toast } from 'sonner';
import {
  Download,
  FileText,
  FileSpreadsheet,
  FileImage,
  Calendar,
  Database
} from 'lucide-react';

// 导出格式类型
type ExportFormat = 'csv' | 'excel' | 'pdf' | 'json' | 'png';

// 数据类型
type DataType = 'stats' | 'activities' | 'system' | 'widgets' | 'all';

// 时间范围
type TimeRange = 'today' | 'week' | 'month' | 'quarter' | 'year' | 'custom';

interface DataExportProps {
  isOpen: boolean;
  onClose: () => void;
  dashboardData?: any;
}

/**
 * 数据导出组件
 * 提供多种格式的数据导出功能
 */
export const DataExport: React.FC<DataExportProps> = ({
  isOpen,
  onClose,
  dashboardData
}) => {
  const [exportFormat, setExportFormat] = useState<ExportFormat>('csv');
  const [dataTypes, setDataTypes] = useState<DataType[]>(['stats']);
  const [timeRange, setTimeRange] = useState<TimeRange>('month');
  const [isExporting, setIsExporting] = useState(false);
  const [includeCharts, setIncludeCharts] = useState(false);
  const [includeMetadata, setIncludeMetadata] = useState(true);

  /**
   * 处理数据类型选择
   */
  const handleDataTypeChange = (dataType: DataType, checked: boolean) => {
    if (checked) {
      setDataTypes(prev => [...prev, dataType]);
    } else {
      setDataTypes(prev => prev.filter(type => type !== dataType));
    }
  };

  /**
   * 获取格式图标
   */
  const getFormatIcon = (format: ExportFormat) => {
    switch (format) {
      case 'csv':
      case 'excel':
        return <FileSpreadsheet className="w-4 h-4" />;
      case 'pdf':
        return <FileText className="w-4 h-4" />;
      case 'png':
        return <FileImage className="w-4 h-4" />;
      case 'json':
        return <Database className="w-4 h-4" />;
      default:
        return <FileText className="w-4 h-4" />;
    }
  };

  /**
   * 模拟数据导出
   */
  const handleExport = async () => {
    setIsExporting(true);
    
    try {
      // 模拟导出延迟
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 构建导出数据
      const exportData = {
        format: exportFormat,
        dataTypes,
        timeRange,
        includeCharts,
        includeMetadata,
        timestamp: new Date().toISOString(),
        data: dashboardData || {}
      };
      
      // 模拟文件下载
      const blob = new Blob([JSON.stringify(exportData, null, 2)], {
        type: 'application/json'
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `dashboard-export-${Date.now()}.${exportFormat}`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      
      toast.success(`数据已成功导出为 ${exportFormat.toUpperCase()} 格式`);
      onClose();
    } catch (error) {
      toast.error('导出失败，请重试');
    } finally {
      setIsExporting(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Download className="w-5 h-5" />
            数据导出
          </DialogTitle>
          <DialogDescription>
            选择要导出的数据类型和格式
          </DialogDescription>
        </DialogHeader>
        
        <div className="space-y-6">
          {/* 导出格式选择 */}
          <div className="space-y-2">
            <Label>导出格式</Label>
            <Select value={exportFormat} onValueChange={(value: ExportFormat) => setExportFormat(value)}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="csv">
                  <div className="flex items-center gap-2">
                    <FileSpreadsheet className="w-4 h-4" />
                    CSV 文件
                  </div>
                </SelectItem>
                <SelectItem value="excel">
                  <div className="flex items-center gap-2">
                    <FileSpreadsheet className="w-4 h-4" />
                    Excel 文件
                  </div>
                </SelectItem>
                <SelectItem value="pdf">
                  <div className="flex items-center gap-2">
                    <FileText className="w-4 h-4" />
                    PDF 文件
                  </div>
                </SelectItem>
                <SelectItem value="json">
                  <div className="flex items-center gap-2">
                    <Database className="w-4 h-4" />
                    JSON 文件
                  </div>
                </SelectItem>
                <SelectItem value="png">
                  <div className="flex items-center gap-2">
                    <FileImage className="w-4 h-4" />
                    PNG 图片
                  </div>
                </SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 数据类型选择 */}
          <div className="space-y-3">
            <Label>数据类型</Label>
            <div className="space-y-2">
              {[
                { id: 'stats', label: '统计数据', desc: '用户数、消息数等关键指标' },
                { id: 'activities', label: '活动记录', desc: '最近的系统活动和操作日志' },
                { id: 'system', label: '系统状态', desc: 'CPU、内存、磁盘使用情况' },
                { id: 'widgets', label: '小部件配置', desc: '当前仪表盘布局和设置' },
                { id: 'all', label: '全部数据', desc: '包含所有可用数据' }
              ].map((item) => (
                <div key={item.id} className="flex items-start space-x-3">
                  <Checkbox
                    id={item.id}
                    checked={dataTypes.includes(item.id as DataType)}
                    onCheckedChange={(checked) => 
                      handleDataTypeChange(item.id as DataType, checked as boolean)
                    }
                  />
                  <div className="grid gap-1.5 leading-none">
                    <label
                      htmlFor={item.id}
                      className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      {item.label}
                    </label>
                    <p className="text-xs text-muted-foreground">
                      {item.desc}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 时间范围选择 */}
          <div className="space-y-2">
            <Label>时间范围</Label>
            <Select value={timeRange} onValueChange={(value: TimeRange) => setTimeRange(value)}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="today">今天</SelectItem>
                <SelectItem value="week">最近一周</SelectItem>
                <SelectItem value="month">最近一月</SelectItem>
                <SelectItem value="quarter">最近一季度</SelectItem>
                <SelectItem value="year">最近一年</SelectItem>
                <SelectItem value="custom">自定义范围</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 附加选项 */}
          <div className="space-y-3">
            <Label>附加选项</Label>
            <div className="space-y-2">
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="charts"
                  checked={includeCharts}
                  onCheckedChange={(checked) => setIncludeCharts(checked as boolean)}
                />
                <label htmlFor="charts" className="text-sm font-medium">
                  包含图表数据
                </label>
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="metadata"
                  checked={includeMetadata}
                  onCheckedChange={(checked) => setIncludeMetadata(checked as boolean)}
                />
                <label htmlFor="metadata" className="text-sm font-medium">
                  包含元数据
                </label>
              </div>
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            取消
          </Button>
          <Button 
            onClick={handleExport} 
            disabled={isExporting || dataTypes.length === 0}
            className="min-w-[100px]"
          >
            {isExporting ? (
              <>
                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2" />
                导出中...
              </>
            ) : (
              <>
                {getFormatIcon(exportFormat)}
                <span className="ml-2">导出数据</span>
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};